package com.zeros.mysplashtwo.http;

import android.text.TextUtils;

import com.zeros.mysplashtwo.MyApplication;
import com.zeros.mysplashtwo.utils.Constants;
import com.zeros.mysplashtwo.utils.ZlogUtilTwo;
import com.zhy.autolayout.utils.L;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.annotations.Nullable;
import okhttp3.Authenticator;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络访问 on 2017/12/22.
 */

public class RetrofitService {

    private static API instance;

    public static API getInstance() {

        //1. 当服务器返回的状态码为401时，会自动执行里面的代码，也就实现了自动刷新token
        Authenticator authenticator = new Authenticator() {
            @Nullable
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                ZlogUtilTwo.e("=============> 重新刷新了token");
                return response.request().newBuilder()
                        .addHeader(Constants.TOKEN_KEY,"")
                        .build();
            }
        };

        //2. 全局拦截器，往请求头部添加token字段，就实现了全局token
        Interceptor tokenInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request tokenRequest;

                if (TextUtils.isEmpty(MyApplication.getToken())) {
                    ZlogUtilTwo.e("MyApplication 的token值为空！！！！！！！！！！！！！");
                    return chain.proceed(originalRequest);
                }
                tokenRequest = originalRequest.newBuilder()
                        .header(Constants.TOKEN_KEY, MyApplication.getToken())
                        .build();
                return chain.proceed(tokenRequest);
            }
        };

        //3. log拦截器，打印所有的log
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                ZlogUtilTwo.e(message);
            }
        });

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(tokenInterceptor)
                .addInterceptor(loggingInterceptor)
                .authenticator(authenticator)
                .build();

        if (instance == null) {
            synchronized (API.class) {
                if (instance == null) {
                    Retrofit retrofit = new Retrofit.Builder()       //生成实例
                            .baseUrl(Constants.BASE_URL)
                            .client(client)
                            .addConverterFactory(GsonConverterFactory.create()) //使用Gson解析
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())  //加入RxJava的适配器
                            .build();

                    instance = retrofit.create(API.class);
                }
            }
        }
        return instance;
    }

}
